<?php namespace App\Services;

use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Message;
use App\Project;
use App\User;
use App\UserInfo;
use Illuminate\Auth\Guard;

class MessageManager
{
    public static function sendSystemMessageToUser($userId,$toUserId,$projectId,$systemMsgType)
    {
        $toUser = User::find($toUserId);
        if(!$toUser)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $message = new Message();
        $message->content   = MessageManager::getSystemMessageContent($systemMsgType);
        $message->type      = 'SystemMessage';
        $message->user_id   = $userId;
        $message->is_read   = 0;
        $message->to_msg_id = null;
        $message->project_id = $projectId;
        $message->toUser()->associate($toUser);

        $message->save();

        return $message;
    }

    public static function getSystemMessageContent($systemMsgType)
    {
        switch($systemMsgType){
            case 'focus.CreaterToInvestor':
                return '您好，#investor#关注了您哦！';
                break;
            case 'focus.InvestorToProject':
                return '您好，投资人#investor#关注了您的项目哦！';
                break;
            case 'watch.InvestorWatchedProject':
                return '您好，投资人#investor#查看了您的项目#project#哦！';
                break;
            case 'invest.InvestToProject':
                return '恭喜，您的项目#project#被投资人#investor# #investtype# #money#,赶快查看吧。';
                break;
            case 'meet.InvestorMeetCreater':
                return '您好，投资人#investor#想约谈您的项目#project#，请保持电话畅通，旁观者创投有专人与您联系。';
                break;
            case 'put.CreaterPutProject':
                return '您好，#investor#将他#project#的商业计划书提交了给您，请您尽快阅读';
                break;
            default:
                return '[UnkownMessage]';
                break;
        }
    }

    public static function getMessage($userId)
    {
        $messages = Message::whereToUserId($userId)->whereIsRead(0)->get();
        foreach($messages as $message){
            $toUserInfo = UserInfo::whereUserId($message->user_id)->first();
            $toProject  = Project::find($message->project_id);
            $message['toUser'] = $toUserInfo;
            $message['toProject'] = $toProject;
        }
        return $messages;
    }
}
